<template>
  <div class="scrollText" ref="outer">
    <div class="st-inner"
         ref="innerInfo"
         :class="{'st-scrolling': needToScroll}"
         :style="scrolling"
    >
      <span class="st-section" ref="inner">{{ text }}</span>
      <span class="st-section" v-if="needToScroll">{{ text }}</span>
      <!-- 加两条是为了滚动的时候实现无缝衔接 -->
    </div>
  </div>
</template>
<script>
import {remToPx} from "@/utils/common";

export default {
  name: 'ScrollX',

  props: {
    speed: {
      default: () => {
        return 5
      },
    },
  },

  data() {
    return {
      needToScroll: false,
      text: '',
      timer: 1,
      scrolling: Object(),
    }
  },

  computed: {
    // 模板的行内样式
    getStyle() {
      return function (val) {
        const self = this;
        if (self.needToScroll) {
          let Obj = Object();
          switch (val) {
            case "scrolling":
              let el = self.$refs.innerInfo;
              if (!!el) {
                let {width} = (el?.getBoundingClientRect());
                let speedRem = parseInt(remToPx(self.speed));
                let time = Math.max(4, Math.ceil(width / speedRem));
                Reflect.set(Obj, 'animation', `scroll ${time}s linear infinite`);
              }
          }
        }
      }
    },
  },

  mounted() {
    this.$nextTick(() => {
      const self = this;
      self.startCheck();
    })
  },

  beforeDestroy() {
    this.stopCheck()
  },

  methods: {
    // 检查当前元素是否需要滚动
    check() {
      this.setText();
      this.$nextTick(() => {
        this.needToScroll = this.isOverflow();
      })
    },

    // 判断子元素宽度是否大于父元素宽度，超出则需要滚动，否则不滚动
    isOverflow() {
      const self = this;
      let Obj = Object();
      let outer = this.$refs.outer;
      let inner = this.$refs.inner;
      let el = this.$refs.innerInfo;
      let outerWidth = null;
      let innerWidth = null;
      if (!!outer && !!inner) {
        outerWidth = this.getWidth(outer);
        innerWidth = this.getWidth(inner);
      }
      if (innerWidth > outerWidth && !!el) {
        let width = this.getWidth(el);
        let speedRem = parseInt(remToPx(self.speed));
        let time = Math.max(6, Math.ceil(width / speedRem));
        Reflect.set(Obj, 'animation', `scroll ${time}s linear infinite`);
        this.scrolling = Obj
      } else {
        this.scrolling = Object()
      }
      return innerWidth > outerWidth;
    },

    // 获取元素宽度
    getWidth(el) {
      let {width} = el.getBoundingClientRect()
      return width;
    },

    // 获取到父组件传过来的内容复传给this.text
    setText() {
      this.text =
          (this.$slots.default &&
              this.$slots.default.reduce((res, it) => res + it.text, '')) ||
          ''
    },

    // 增加定时器，隔一秒check一次
    startCheck() {
      this._checkTimer = setInterval(this.check, 1000)
      this.check()
    },

    // 关闭定时器
    stopCheck() {
      clearInterval(this._checkTimer)
    }
  }
}
</script>
<style lang="scss">

.scrollText {
  overflow: hidden;
  width: 100%;
  height: 100%;
  display: inline-flex;
  align-items: center;
  align-self: center;
  white-space: nowrap;
}

.st-inner {
  margin: 0 auto;
  display: inline-block;
}

.st-scrolling .st-section {
  padding: 0 5px !important;
  box-sizing: border-box;
}

// 向左匀速滚动动画
.st-scrolling {
  animation: scroll 10s linear infinite;
}

@keyframes scroll {
  0% {
    transform: translate3d(0%, 0, 0);
  }
  100% {
    transform: translate3d(-50%, 0, 0);
  }
}
</style>
